package com.huawang.ecolink.apps.common;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Comparator;

public class VersionCompare {

    private VersionCompare() {

    }

    /***
     * @Description: 版本比对方法
     * @param
     * @return: java.util.Comparator<java.lang.String>
     * @throws:
     */
    public static Comparator<String> getComparator() {
        return (v1, v2) -> {
            if (v1.equals(v2) || !isNumeric(v1) || !isNumeric(v2)) {
                return 0;
            } else {
                String[] version1Array = v1.split("[._]");
                String[] version2Array = v2.split("[._]");
                int index = 0;
                int minLen = Math.min(version1Array.length, version2Array.length);
                long diff = 0;
                while (index < minLen && (diff = Long.parseLong(version1Array[index]) - Long.parseLong(version2Array[index])) == 0) {
                    index++;
                }
                return extracted(version1Array, version2Array, index, diff);
            }
        };
    }

    /***
     * @Description: 排序
     * @param version1Array String[]
     * @param version2Array String[]
     * @param index int
     * @param diff long
     * @return: int
     * @throws:
     */
    private static int extracted(String[] version1Array, String[] version2Array, int index, long diff) {
        if (diff == 0) {
            for (int i = index; i < version1Array.length; i++) {
                if (Long.parseLong(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Long.parseLong(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    /***
     * @Description: 判断是否为数字类型
     * @param str String
     * @return: boolean
     * @throws:
     */
    private static boolean isNumeric(String str) {
        return StringUtils.isNumeric(str) || Arrays.stream(str.split("\\.")).allMatch(s -> StringUtils.isNumeric(s));
    }

}
